
package com.shop.cloud.weixin.admin.handler;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.shop.cloud.common.data.tenant.TenantContextHolder;
import com.shop.cloud.weixin.admin.service.WxAppService;
import com.shop.cloud.weixin.admin.service.WxMaNicknameAuditService;
import com.shop.cloud.weixin.common.constant.WxConstant;
import com.shop.cloud.weixin.common.entity.WxApp;
import com.shop.cloud.weixin.common.entity.WxMaNicknameAudit;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 小程序名称审核结果事件推送
 * @author
 */
@Slf4j
@Component
@AllArgsConstructor
public class NickNameAuditHandler extends AbstractHandler {

	private final WxAppService wxAppService;
	private final WxMaNicknameAuditService wxmaNicknameAuditService;

	@Override
	public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService,
			WxSessionManager sessionManager) {
		WxApp wxApp = wxAppService.findByWeixinSign(wxMessage.getToUser());
		TenantContextHolder.setTenantId(wxApp.getTenantId());//加入租户ID
		Map<String, Object> allFieldsMap = wxMessage.getAllFieldsMap();
		String ret = (String) allFieldsMap.get("ret");
		String reason = (String) allFieldsMap.get("reason");
		String nickname = (String) allFieldsMap.get("nickname");
		WxMaNicknameAudit wxMaNicknameAudit = wxmaNicknameAuditService.getOne(Wrappers.<WxMaNicknameAudit>query().lambda()
				.eq(WxMaNicknameAudit::getAppId,wxApp.getId())
				.eq(WxMaNicknameAudit::getNickname,nickname)
				.orderByDesc(WxMaNicknameAudit::getCreateTime)
				.last("limit 1"));
		wxMaNicknameAudit.setRet(ret);
		wxMaNicknameAudit.setReason(reason);
		//更新数据库
		wxmaNicknameAuditService.updateById(wxMaNicknameAudit);
		if(WxConstant.WX_NICKNAME_AUDIT_RET_3.equals(ret)){
			//成功则更新Wxapp
			wxApp.setName(nickname);
			wxAppService.updateById(wxApp);
		}
		return null;
	}

}
